<?php

/**
 * Acl manager
 *
 * @category CMS
 * @package CMS_Acl
 * @version 1.0
 */
class CMS_Acl extends Zend_Acl
{

    /**
     * CMS_Acl instance
     * @var CMS_Acl
     */
    private static $instance;

    /**
     * Returns an instance of CMS_Acl
     *
     * @return CMS_Acl
     */
    public static function getInstance()
    {
        if (!isset(self::$instance))
            self::$instance = self::createInstance();

        return self::$instance;
    }

    /**
     * Returns true if and only if the audience has access to the resource
     *
     * @param  Zend_Acl_Resource_Interface|string $resource
     * @param  string $privilege
     *
     * @return boolean
     */
    public function hasPermission($resource, $privilege = null)
    {
        $audience = $this->getAudience();
        return parent::isAllowed($audience, $resource, $privilege);
    }

    /**
     * Looks if acl object is cached,
     * otherwise creates a new instance and stores it in the cache
     *
     * @return CMS_Acl
     */
    private static function createInstance()
    {
        $className = __CLASS__;
        $instance = new $className();
        return $instance;
    }

    private function __construct()
    {
        $this->addStaticResources();
        $this->addSiteResourcesAndAudiences();
    }

    /**
     * Returns the current user audience, or guest if not logged in
     *
     * @return integer|string audience
     */
    private function getAudience()
    {
        if (Zend_Auth::getInstance()->hasIdentity())
            return Zend_Auth::getInstance()->getIdentity()->type;

        try
        {
            $site = CMS_Site_Business::getSite();
        }
        catch (CMS_Site_Exception $e)
        {
            return NULL;
        }

        return Audience::findOnePublic($site->id)->id;
    }
    
}
